import axios from 'axios'
import router from '../router'
import querystring from 'querystring'

const service = axios.create({
  baseURL: 'https://ethrct.itobox.io',
  timeout: 10000
})

// 拦截器
service.interceptors.request.use(config => {
  if(!config.params){
    config.params = {}
  }
  let coin_type = window.location.host.split('.')[0]
  config.params.coin_type = coin_type
  if ((config.data && config.data.head === 1) || (config.params && config.params.head === 1)) {
    let token = JSON.parse(window.sessionStorage.getItem('TOKEN') || window.localStorage.getItem('LOCALTOKEN') || '{ "access_token": "" }')
    // console.log(token)
    if (token.access_token) {
      config.headers = {
        Authorization: `${token.token_type} ${token.access_token}`
      }
    }
  }
  if (
    // config.method === 'post' ||
    config.method === 'put' ||
    config.method === 'delete'
  ) {
    config.data = querystring.stringify(config.data)
  }
  if (config.method === 'post') {
    config.headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'
    config.data = querystring.stringify(config.data)
  }
  return config
}, error => {
  return Promise.reject(error)
})

service.interceptors.response.use(response => {
  if (response.data.RET === 2) {
    // window.localStorage.setItem('LOCALTOKEN', '{ "access_token": "" }')
    // window.sessionStorage.setItem('TOKEN', '{ "access_token": "" }')
    router.replace('/login')
  }
  if (response.data.code === 50001) {
    // notice(response.data.message)
    // console.log(router)
    // window.localStorage.setItem('LOCALTOKEN', '{ "access_token": "" }')
    // window.sessionStorage.setItem('TOKEN', '{ "access_token": "" }')
    router.replace('/login')
  }
  if (response.data.message === '余额不足') {
    router.replace('/two')
    document.querySelector('#app').scrollTop = 500
  }
  return response
}, error => {
  return Promise.reject(error)
})

export default service
